import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'
import axios from 'axios'

// 文案提取接口
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { videoId, method = 'OCR' } = await request.json()

    if (!videoId) {
      return NextResponse.json(
        { error: '视频ID不能为空' },
        { status: 400 }
      )
    }

    // 检查视频是否存在
    const video = await prisma.tikTokVideo.findUnique({
      where: { id: videoId }
    })

    if (!video) {
      return NextResponse.json(
        { error: '视频不存在' },
        { status: 404 }
      )
    }

    // 检查是否已有提取记录
    const existingExtraction = await prisma.textExtraction.findFirst({
      where: {
        videoId,
        method,
        status: 'completed'
      }
    })

    if (existingExtraction) {
      return NextResponse.json({
        message: '文案已提取',
        extraction: existingExtraction
      })
    }

    // 创建提取记录
    const extraction = await prisma.textExtraction.create({
      data: {
        videoId,
        extractedText: '',
        method,
        status: 'pending'
      }
    })

    // 调用文案提取服务
    try {
      const extractedData = await extractTextFromVideo(video.url, method)
      
      // 更新提取记录
      const updatedExtraction = await prisma.textExtraction.update({
        where: { id: extraction.id },
        data: {
          extractedText: extractedData.text,
          confidence: extractedData.confidence,
          language: extractedData.language,
          status: 'completed'
        }
      })

      return NextResponse.json({
        message: '文案提取成功',
        extraction: updatedExtraction
      })

    } catch (extractError) {
      // 更新提取记录为失败状态
      await prisma.textExtraction.update({
        where: { id: extraction.id },
        data: {
          status: 'failed'
        }
      })

      throw extractError
    }

  } catch (error) {
    console.error('Text extraction error:', error)
    return NextResponse.json(
      { error: '文案提取失败' },
      { status: 500 }
    )
  }
}

// 获取视频的文案提取记录
export async function GET(request: NextRequest) {
  try {
    const user = getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { searchParams } = new URL(request.url)
    const videoId = searchParams.get('videoId')

    if (!videoId) {
      return NextResponse.json(
        { error: '视频ID不能为空' },
        { status: 400 }
      )
    }

    const extractions = await prisma.textExtraction.findMany({
      where: { videoId: parseInt(videoId) },
      orderBy: { createdAt: 'desc' }
    })

    return NextResponse.json({ extractions })

  } catch (error) {
    console.error('Get extractions error:', error)
    return NextResponse.json(
      { error: '获取提取记录失败' },
      { status: 500 }
    )
  }
}

// 文案提取服务（模拟实现）
async function extractTextFromVideo(videoUrl: string, method: string) {
  // 这里应该调用实际的文案提取API
  // 可以是OCR服务、ASR服务等
  
  try {
    // 模拟API调用
    // 实际项目中需要替换为真实的文案提取API
    
    if (method === 'OCR') {
      // 模拟OCR提取
      return {
        text: '这是通过OCR提取的视频文案内容，包含了视频中的文字信息。',
        confidence: 0.85,
        language: 'zh-CN'
      }
    } else if (method === 'ASR') {
      // 模拟ASR提取
      return {
        text: '这是通过语音识别提取的视频文案内容，包含了视频中的语音信息。',
        confidence: 0.92,
        language: 'zh-CN'
      }
    } else {
      throw new Error('不支持的提取方法')
    }

  } catch (error) {
    console.error('Failed to extract text:', error)
    throw new Error('文案提取服务调用失败')
  }
}
